﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Lesson01_同步_服务端_Exercises2
{
    internal class ClientSocket
    {
        private static int CLIENT_BEING_ID = 1;
        public int clientId;
        public Socket socket;

        public ClientSocket(Socket socket)
        {
            this.clientId = CLIENT_BEING_ID;
            this.socket = socket;
            CLIENT_BEING_ID++;
        }

        public int ClientId => this.clientId;

        //连接状态处理
        public bool IsConnected => this.socket.Connected;

        public void Close()
        {
            if (socket == null)
                return;
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            socket = null;
        }

        public void Send(string data)
        {
            if (socket == null)
                return;
            try
            {
                socket.Send(Encoding.UTF8.GetBytes(data));
            }
            catch (Exception e)
            {
                Console.WriteLine("[ClientSocket][Send] Fail(Id:{0} Error:{1})", clientId, e.Message);
                Close();
            }
        }
        public void Receive()
        {
            if (socket == null)
                return;
            if (socket.Available == 0)
                return;
            byte[] result = new byte[1024 * 1024];
            try
            {
                int recvLen = socket.Receive(result);
                ThreadPool.QueueUserWorkItem(MsgHandle, Encoding.UTF8.GetString(result, 0, recvLen));
            }
            catch (Exception e)
            {
                Console.WriteLine("[ClientSocket][Receive] Fail(Id:{0} Error:{1})", clientId, e.Message);
            }
        }

        private void MsgHandle(object obj)
        {
            if (socket == null)
                return;
            try
            {
                string str = obj as string;
                Console.WriteLine("[ClientSocket][MsgHandle] Client:{0} Msg:{1}", clientId, str);
            }
            catch (Exception e)
            {
                Console.WriteLine("[ClientSocket][MsgHandle] Fail(Id:{0} Error:{1})", clientId, e.Message);
            }
        }
    }
}
